package com.controller.teacherlist;

import com.entity.Teacher;
import com.util.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/associates")
public class ListAssociateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Teacher> associates = new ArrayList<>();
        String sql = "select * from teachers";
        try(Connection conn = DataSourceUtils.getConnection();
            PreparedStatement st = conn.prepareStatement(sql)) {
            try (ResultSet rs = st.executeQuery()) {
                while (rs.next()) {
                    if(rs.getString("grade").equals("associate")) {
                        Teacher teacher = new Teacher();
                        teacher.setId(rs.getInt("id"));
                        teacher.setName(rs.getString("name"));
                        teacher.setGrade(rs.getString("grade"));
                        teacher.setImage(rs.getString("img"));
                        teacher.setIntroduction(rs.getString("intro"));
                        associates.add(teacher);
                    }
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        req.setAttribute("associates", associates);
        req.getRequestDispatcher("/WEB-INF/teachers/associates.jsp").forward(req, resp);
    }
}
